package com.yunlong.service.impl;

import com.yunlong.common.exception.SysException;
import com.yunlong.dto.MessageDto;
import com.yunlong.redis.RedisRepository;
import com.yunlong.service.MessageService;
import com.yunlong.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.language.bm.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author ycSong
 * @create 2020/8/13 15:05
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private RedisRepository redisRepository;
    @Resource
    private MessageUtil messageUtil;

    @Override
    public MessageDto getSsm(String number) {
        if (number.equals("") || number == null) {
            throw new SysException("没有填写手机号");
        }
        /*
          验证是否发送过
                  String codeTemp = redisRepository.selectMessageCodeByPhone(number.getNumber());
                  if (codeTemp!=null){
                      throw new SysException ("不能重复发送");
                 }
         */
        //随机生成六位验证码
        int phoneCode = (int) ((Math.random() * 9 + 1) * 100000);
        MessageDto messageDto = messageUtil.getSsm(number, String.valueOf(phoneCode));
        if("OK".equals(messageDto.getState())) {
            redisRepository.saveMessageCode(number, String.valueOf(phoneCode));
        }


        return messageDto;
    }

    /**
     * 注册时发送邮箱给用户
     *
     * @param email
     * @return MessageDto
     */
    @Override
    public MessageDto sendEmailOfRegister(String email) {
        //随机生成六位验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String code1 = Integer.toString(code);
        MessageDto messageDto = messageUtil.sendEmailOfRegister(email, code1);
        if (messageDto.isOk() == true) {
            redisRepository.saveEmailMessageCode(email, String.valueOf(code));
        }
        return messageDto;
    }
}
